package com.mdp.workflow.bus.candidate.strategy;

import com.mdp.core.err.BizException;
import com.mdp.core.utils.CollectionUtils;
import com.mdp.workflow.api.FlowProcinstService;
import com.mdp.workflow.bus.candidate.TaskCandidateStrategy;
import com.mdp.workflow.comm.dict.CandidateStrategy;
import com.mdp.workflow.comm.dict.ProcinstConstants;
import com.mdp.workflow.comm.tools.FlowableUtils;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 9哥
 *
 * @author 参考芋道源码 ，由唛盟开源改造
 */
@Component
public class NextUserStrategy implements TaskCandidateStrategy {


    @Override
    public com.mdp.workflow.comm.dict.CandidateStrategy getStrategy() {
        return CandidateStrategy.NEXT_ASSIGNEES;
    }

    @Override
    public void validateParam(String param) {

    }

    @Override
    public Set<String> calculateUsers(DelegateExecution execution, String param) {
        Map<String,Object> flowVars=execution.getVariables();
        List<String> nextAssignees= (List<String>) flowVars.get(ProcinstConstants.NEXT_ASSIGNEES);
        FlowElement element=execution.getCurrentFlowElement();
        if(element instanceof UserTask){
            UserTask task=(UserTask)element;
            if(task.hasMultiInstanceLoopCharacteristics()){
                if(nextAssignees==null){
                    throw new BizException("need-multiple-assignee","请选定多个候选人");
                }
            }else{
                if(nextAssignees==null){
                    throw new BizException("need-single-assignee","请选定1个审批人");
                }
            }
            setMultiInstanceParams(execution);
            return CollectionUtils.convertSet(nextAssignees);
        }else{
            return new LinkedHashSet<>();
        }
    }


    public void setMultiInstanceParams(DelegateExecution execution){
        /**
         * 另附判断结果类中流程引擎自带可用变量：
         1.nrOfInstances 该会签环节中总共有多少个实例

         2.nrOfActiveInstances 当前活动的实例的数量，即还没有 完成的实例数量。

         3.nrOfCompletedInstances 已经完成的实例的数量

         4.nrOfAgree 同意个数

         5.nrOfDisAgree 不同意个数

         2.nrOfActiveInstances 当前活动的实例的数量，即还没有 完成的实例数量。
         3.nrOfCompletedInstances 已经完成的实例的数量
         4.nrOfAgree 同意个数
         5.nrOfDisAgree 不同意个数
         */
        // int completedInstance = (int)execution.getVariable("nrOfCompletedInstances");
        // int nrOfInstances = (int)execution.getVariable("nrOfInstances");
        // 自定义两个变量，用于事先过半同意，会签成功等场景
        execution.setVariable("nrOfAgree", 0);
        execution.setVariable("nrOfDisAgree", 0);

    }

    @Override
    public boolean isParamRequired() {
        return false;
    }



}
